<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import { storeApi, foodApi } from "@/api/customer";
import type { Store, Food, Category } from "@/types/customer";
import { ElMessage } from "element-plus";
import { formatImageUrl } from "@/utils/image";

const router = useRouter();
const categories = ref<Category[]>([]);
const recommendedStores = ref<Store[]>([]);
const featuredFoods = ref<Food[]>([]);
const loading = ref({
  categories: true,
  stores: true,
  foods: true,
});

// 获取默认分类图标（参考微信小程序逻辑）
const getDefaultCategoryIcon = (categoryName: string) => {
  const iconMap: Record<string, string> = {
    '快餐': '/images/category/fast-food.png',
    '火锅': '/images/category/hot-pot.png',
    '中餐': '/images/category/chinese.png',
    '西餐': '/images/category/western.png',
    '日料': '/images/category/japanese.png',
    '韩餐': '/images/category/korean.png',
    '甜点': '/images/category/dessert.png',
    '饮品': '/images/category/drinks.png',
    '小吃': '/images/category/snacks.png',
    '素食': '/images/category/vegetarian.png',
    '早餐': '/images/category/breakfast.png',
    '米粉': '/images/category/rice-noodles.png',
    '面条': '/images/category/noodles.png',
    '炸鸡': '/images/category/fried-chicken.png',
    '烧烤': '/images/category/bbq.png',
  };
  return iconMap[categoryName] || '/images/category/more.png';
};

// 获取用户地理位置（参考微信小程序逻辑）
const getUserLocation = (): Promise<{ longitude: number; latitude: number } | null> => {
  return new Promise((resolve) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          resolve({
            longitude: position.coords.longitude,
            latitude: position.coords.latitude
          });
        },
        (error) => {
          console.warn('获取位置失败:', error);
          resolve(null); // 获取位置失败时返回null，但不影响后续操作
        },
        {
          timeout: 10000,
          enableHighAccuracy: false
        }
      );
    } else {
      console.warn('浏览器不支持地理位置功能');
      resolve(null);
    }
  });
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value.categories = true;
    // 使用正确的API接口 - storeApi.getCategories() 实际调用的是 /categories
    const res = await storeApi.getCategories();
    
    if (res && res.data) {
      // 处理不同的响应格式
      let categoriesData: any[] = [];
      if (Array.isArray(res.data)) {
        categoriesData = res.data;
      } else if (res.data.data && Array.isArray(res.data.data)) {
        categoriesData = res.data.data;
      }
      
      // 处理分类数据，参考微信小程序逻辑
      categories.value = categoriesData.map((category: any) => {
        // 处理图标URL，优先使用服务端返回的图标
        let icon = category.icon;
        // 如果图标URL不存在或无效，使用默认图标
        if (!icon || (!icon.startsWith('http') && !icon.startsWith('/'))) {
          icon = getDefaultCategoryIcon(category.name);
        }
        
        return {
          ...category,
          icon: icon,
          sort: category.sort || 0
        };
      }).sort((a, b) => (a.sort || 0) - (b.sort || 0)); // 按sort字段排序
    } else {
      categories.value = [];
    }
  } catch (error) {
    console.error("获取分类失败:", error);
    ElMessage.error("获取分类信息失败");
    categories.value = [];
  } finally {
    loading.value.categories = false;
  }
};

// 获取推荐商家
const fetchRecommendedStores = async () => {
  try {
    loading.value.stores = true;
    
    // 获取用户位置（参考微信小程序逻辑）
    const location = await getUserLocation();
    
    // 构造请求参数
    const params: any = location ? {
      longitude: location.longitude,
      latitude: location.latitude,
      page: 1,
      pageSize: 10
    } : { page: 1, pageSize: 10 };
    
    const res = await storeApi.getRecommended(params);
    
    if (res && res.data) {
      // 处理不同的响应格式
      let storesData: any[] = [];
      if (Array.isArray(res.data)) {
        storesData = res.data;
      } else if (res.data.data && Array.isArray(res.data.data)) {
        storesData = res.data.data;
      }
      
      // 从响应中获取店铺列表并处理数据（参考微信小程序）
      recommendedStores.value = storesData.map((store: any) => ({
        ...store,
        // 修复：使用logo字段作为coverImage，并处理图片URL
        coverImage: formatImageUrl(store.logo || store.coverImage),
        // 预处理距离显示
        formattedDistance: store.distance ? (store.distance / 1000).toFixed(1) : null,
        // 确保必要字段有默认值
        monthSales: store.monthSales || store.monthlySales || 0,
        rating: store.rating || 0,
        tags: store.tags || [],
        deliveryTime: store.deliveryTime || store.averageDeliveryTime || 30,
        distance: store.distance || 0,
        minOrder: store.minOrder || store.minOrderAmount || 0
      }));
    } else {
      recommendedStores.value = [];
    }
  } catch (error) {
    console.error("获取推荐商家失败:", error);
    ElMessage.error("获取推荐商家失败，请稍后重试");
    recommendedStores.value = [];
  } finally {
    loading.value.stores = false;
  }
};

// 跳转到分类页
const goToCategory = (categoryId: number) => {
  router.push(`/customer/search?category=${categoryId}`);
};

// 跳转到商家详情页
const goToStore = (storeId: number) => {
  router.push(`/customer/store/${storeId}`);
};

// 跳转到食品详情页
const goToFood = (foodId: number) => {
  router.push(`/customer/food/${foodId}`);
};

// 页面加载时获取数据
onMounted(() => {
  fetchCategories();
  fetchRecommendedStores();
});
</script>

<template>
  <CustomerLayout>
    <!-- 分类区域 -->
    <section class="categories-section">
      <h2 class="section-title">美食分类</h2>
      <el-skeleton :rows="1" animated v-if="loading.categories" />
      <div class="categories-list" v-else>
        <div 
          v-for="category in categories" 
          :key="category.id" 
          class="category-item"
          @click="goToCategory(category.id)"
        >
          <div class="category-icon">
            <img :src="formatImageUrl(category.icon)" :alt="category.name" />
          </div>
          <div class="category-name">{{ category.name }}</div>
        </div>
      </div>
    </section>

    <!-- 推荐商家区域 -->
    <section class="stores-section">
      <h2 class="section-title">推荐商家</h2>
      <el-skeleton :rows="2" animated v-if="loading.stores" />
      <div class="stores-list" v-else>
        <div 
          v-for="store in recommendedStores" 
          :key="store.id" 
          class="store-card"
          @click="goToStore(store.id)"
        >
          <div class="store-image">
            <img :src="store.coverImage" :alt="store.name" />
          </div>
          <div class="store-info">
            <h3 class="store-name">{{ store.name }}</h3>
            <div class="store-rating">
              <el-rate 
                v-model="store.rating" 
                disabled 
                text-color="#FF9900"
                show-score 
                score-template="{value}" 
              />
              <span class="monthly-sales">月售 {{ store.monthSales }}+</span>
            </div>
            <div class="store-tags">
              <el-tag 
                v-for="(tag, index) in store.tags" 
                :key="index" 
                size="small" 
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="store-delivery">
              <span>{{ store.deliveryTime }}分钟</span>
              <span>{{ store.distance }}km</span>
              <span>起送¥{{ store.minOrder }}</span>
            </div>
          </div>
        </div>
      </div>
    </section>

  </CustomerLayout>
</template>

<style scoped>
/* 分类区域样式 */
.categories-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 24px;
  color: #8b4513;
  margin-bottom: 20px;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: #ffd54f;
  border-radius: 2px;
}

.categories-list {
  display: flex;
  overflow-x: auto;
  padding: 10px 0;
  gap: 20px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  min-width: 80px;
}

.category-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #fff3cd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.category-icon img {
  width: 36px;
  height: 36px;
}

.category-name {
  font-size: 14px;
  color: #8b4513;
}

/* 商家列表样式 */
.stores-section {
  margin-bottom: 30px;
}

.stores-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.store-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s;
  display: flex;
  align-items: flex-start;
  padding: 15px;
}

.store-card:hover {
  transform: translateY(-5px);
}

.store-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 8px;
  flex-shrink: 0;
  margin-right: 15px;
}

.store-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.store-info {
  flex: 1;
}

.store-name {
  font-size: 18px;
  margin: 0 0 10px;
  color: #8b4513;
}

.store-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.monthly-sales {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}

.store-tags {
  margin-bottom: 10px;
}

.store-delivery {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

/* 食品列表样式 */
.foods-section {
  margin-bottom: 30px;
}

.foods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.food-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s;
}

.food-card:hover {
  transform: translateY(-5px);
}

.food-image {
  height: 120px;
  overflow: hidden;
}

.food-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-info {
  padding: 12px;
}

.food-name {
  font-size: 16px;
  margin: 0 0 5px;
  color: #8b4513;
}

.food-store {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.food-rating {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.food-price {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stores-list, .foods-list {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
  }
}
</style>
